import Vue            from 'vue'
import { apiRequest } from "../../assets/fetch";

export default {
    namespaced: true,
    state     : {
        data       : {},
        all        : [],
        accounts   : [],
        accountMeta: {},
    },
    mutations : {
        saveData(state, {
            data,
            type
        }) {
            Vue.set(state.data, type, data);
        },
        saveAll(state, data) {
            state.all = data;
        },
        accounts(state, data) {
            state.accounts = data;
        },
        accountMeta(state, meta) {
            console.log('meta :', meta);
            state.accountMeta = meta;
        }
    },
    actions   : {
        async accounts({ commit }, data = {}) {
            let res = await apiRequest('ACCOUNT_INDEX', { data });

            if (res.result) {
                commit('accounts', res.data.data);
                commit('accountMeta', res.data.meta);
            }
            return res;
        },
        async getDataForType({ commit }, data) {

            let type = data.type;
            let res  = await apiRequest('CLUE_INDEX', {
                data,
            });

            if (res.result) {
                type ? commit('saveData', {
                    data: res.data,
                    type
                }) : commit('saveAll', res.data);
            }

            return res;
        },
        async createData(_, data) {
            let res = await apiRequest('ACCOUNT_CREATE', {
                data,
            });
            return res;
        },
        async updateData(_, data) {
            let id = data.id;
            return await apiRequest('ACCOUNT_UPDATE', {
                data,
            }, id);
        },
        async deleteData(_, id) {
            return await apiRequest('ACCOUNT_DELETE', {}, id);
        }
    }
}
